package hk.m4s.lr.repair.test.utils;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class AppTools {
	private static List<Activity> activityList = new ArrayList<Activity>();

	public static void pushActivity(Activity activity){
		if(!activityList.contains(activity)){
			activityList.add(0,activity);
		}
	}

	public static void popActivity(Activity activity){
		activityList.remove(activity);
	}

	/**
	 * 功能说明： 获取系统当前时间
	 * <p>
	 * 
	 * @param pattern
	 * @return
	 */
	public static String getTime(String pattern) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		return dateFormat.format(new Date());
	}




	public static BitmapFactory.Options getBitmapOption(int inSampleSize){
		System.gc();
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPurgeable = true;
		options.inSampleSize = inSampleSize;
		return options;
	}
	/**
	 * 功能说明： 将uri 转换为绝对路径 </p>
	 * 
	 * @param context
	 * @param uri
	 * @return
	 */
	public static String getAbsolutePath(Context context, Uri uri) {
		if (uri == null) {
			return null;
		}
		if (uri.toString().contains("file://")) {

			String path = uri.toString().replace("file://", "");

			return Uri.decode(path);
		}
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.getContentResolver().query(uri, proj, null,
				null, null);
		if (cursor == null) {
			return null;
		}
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();
		return cursor.getString(column_index);

	}


	/**
	 * 获取压缩图片文件存取路径
	 * 
	 * @return
	 */
	public static String getImageCompresPath() {
		if (AppTools.getSDPath().equals("")) {
			return "";
		}
		File file = new File(AppTools.getSDPath()
				+ "/supermarket_photo/COMPRES");
		if (!file.exists()) {
			if (file.mkdirs()) {
				return file.getPath();
			}
			return "";
		}
		return file.getPath();
	}

	public static boolean checkNetworkConnection(Context context) {
		final ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		final NetworkInfo wifi = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		final NetworkInfo mobile = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (wifi.isAvailable() || mobile.isAvailable())
			return true;
		else
			return false;
	}

	/**
	 * 功能说明： 判断SD卡是否存在, 如果存在返回SD卡路径 , 如果不存在返回路径为空</p>
	 * 
	 * @return
	 */
	public static String getSDPath() {
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		if (sdCardExist) {
			File sdDir = Environment.getExternalStorageDirectory();
			return sdDir.toString();
		}
		return "";
	}

	/**
	 * 判断sd卡的剩余容量
	 * 
	 * @return
	 */
	public static long getSDAvailableStore() {
		// 取得sdcard文件路径
		StatFs statFs = new StatFs(getSDPath());
		// 获取block的SIZE
		long blocSize = statFs.getBlockSize();
		// 获取BLOCK数量
		long totalBlocks = statFs.getBlockCount();
		// 可使用的Block的数量
		long availaBlock = statFs.getAvailableBlocks();
		long total = totalBlocks * blocSize;
		long availableSpare = availaBlock * blocSize;
		return availableSpare;
	}

	/**
	 * 图片无损压缩
	 * 
	 * @param fromPath
	 *            图片来源路径
	 * @param toPath
	 *            目標存儲路徑
	 * @param width
	 *            最長邊壓縮到的長度
	 */
//	public static String compressImage(String toPath, int width) {
//		String fromPath = CameraManager.intance().getCameraPath();
//		// LogUtil.i("fromPath  : " + fromPath + " ; toPath : " + toPath);
//		BitmapFactory.Options options = new BitmapFactory.Options();
//		options.inJustDecodeBounds = true;
//		Bitmap bitmap = BitmapFactory.decodeFile(fromPath, options);
//		int be;
//		// 缩放比
//		if (options.outWidth > options.outHeight) {
//			be = (int) (options.outWidth / width);
//			be = be + ((options.outWidth % width == 0) ? 0 : 1);
//		} else {
//			be = (int) (options.outHeight / (float) width);
//			be = be + ((options.outHeight % width == 0) ? 0 : 1);
//		}
//		if (be <= 0) {
//			be = 1;
//		}
//		options.inSampleSize = be;
//		options.inJustDecodeBounds = false;
//		bitmap = BitmapFactory.decodeFile(fromPath, options);
//		File file = new File(toPath);
//		try {
//			FileOutputStream out = new FileOutputStream(file);
//			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out)) {
//				out.flush();
//				out.close();
//			}
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return toPath;
//	}

	/**
	 * 图片无损压缩
	 * 
	 * @param fromPath
	 *            图片来源路径
	 * @param toPath
	 *            目標存儲路徑
	 * @param width
	 *            最長邊壓縮到的長度
	 */
//	public static String zipImage(String fromPath, String toPath, int width) {
//		LogUtil.i("fromPath  : " + fromPath + " ; toPath : " + toPath);
//		BitmapFactory.Options options = new BitmapFactory.Options();
//		options.inJustDecodeBounds = true;
//		Bitmap bitmap = BitmapFactory.decodeFile(fromPath, options);
//		int be;
//		// 缩放比
//		if (options.outWidth > options.outHeight) {
//			be = (int) (options.outWidth / width);
//			be = be + ((options.outWidth % width == 0) ? 0 : 1);
//		} else {
//			be = (int) (options.outHeight / (float) width);
//			be = be + ((options.outHeight % width == 0) ? 0 : 1);
//		}
//		if (be <= 0) {
//			be = 1;
//		}
//		options.inSampleSize = be;
//		options.inJustDecodeBounds = false;
//		bitmap = BitmapFactory.decodeFile(fromPath, options);
//		File file = new File(toPath);
//		try {
//			FileOutputStream out = new FileOutputStream(file);
//			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 30, out)) {
//				out.flush();
//				out.close();
//			}
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return toPath;
//	}

	
	public static Bitmap getSmall(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
		if (bitmap == null) {

		}
		float realWidth = options.outWidth;
		float realHeight = options.outHeight;
		// 计算缩放比
		int scale = (int) ((realHeight > realWidth ? realHeight : realWidth) / 100);
		if (scale <= 0) {
			scale = 1;
		}
		options.inSampleSize = scale;
		options.inJustDecodeBounds = false;
		// 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。
		bitmap = BitmapFactory.decodeFile(filePath, options);
		return bitmap;
	}

	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		options.inSampleSize = calculateInSampleSize(options, 480, 800);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	// 计算图片的缩放值
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	/**
	 * 读取图片属性：旋转的角度
	 * 
	 * @param path
	 *            图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/*
	 * 旋转图片
	 * 
	 * @param angle
	 * 
	 * @param bitmap
	 * 
	 * @return Bitmap
	 */
	public static Bitmap rotaingImageView(int degree, Bitmap bitmap) {
		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图片
			returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight(), matrix, true);
		} catch (OutOfMemoryError e) {
		}
		// if (returnBm == null) {
		// returnBm = bitmap;
		// }
		if (bitmap != null) {
			bitmap.recycle();

		}
		return returnBm;
	}

	public static void setPictureDegreeZero(String path) {
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			// 修正图片的旋转角度，设置其不旋转。这里也可以设置其旋转的角度，可以传值过去，
			// 例如旋转90度，传值ExifInterface.ORIENTATION_ROTATE_90，需要将这个值转换为String类型的
			exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "no");
			exifInterface.saveAttributes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static Drawable convertBitmap2Drawable(Bitmap bitmap) {
		BitmapDrawable bd = new BitmapDrawable(bitmap);
		// 因为BtimapDrawable是Drawable的子类，最终直接使用bd对象即可。
		return bd;
	}

	public static boolean isConnect(Context context) {
		ConnectivityManager conManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo networkInfo = conManager.getActiveNetworkInfo();

		if (networkInfo != null) { // 注意，这个判断一定要的哦，要不然会出错

			return networkInfo.isAvailable();

		}

		return false;

	}

	public static boolean IsStartWifi(final Context context) {
		try {
			WifiManager wm = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			return (wm != null && WifiManager.WIFI_STATE_ENABLED == wm
					.getWifiState());
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * 利用Volley异步加载图片
	 * 
	 * 注意方法参数: getImageListener(ImageView view, int defaultImageResId, int
	 * errorImageResId) 第一个参数:显示图片的ImageView 第二个参数:默认显示的图片资源 第三个参数:加载错误时显示的图片资源
	 */
//	public static void loadImage(String url, ImageView imageView,
//			RequestQueue queue) {
//
//		if (url == null || url.length() <= 0) {
//			return;
//		}
//		StringBuffer imageUrl = new StringBuffer(Constant.ConValue.PHOTO_PATH);
//		imageUrl.append(url);
//		LogUtil.i("loadImageUrl:" + imageUrl);
//		final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(
//				20);
//		ImageCache imageCache = new ImageCache() {
//			@Override
//			public void putBitmap(String key, Bitmap value) {
//				lruCache.put(key, value);
//			}
//
//			@Override
//			public Bitmap getBitmap(String key) {
//				return lruCache.get(key);
//			}
//		};
//		ImageLoader imageLoader = new ImageLoader(queue, imageCache);
//		ImageListener listener = ImageLoader.getImageListener(imageView,
//				R.drawable.ic_launcher, R.drawable.ic_launcher);
//		imageLoader.get(imageUrl.toString(), listener);
//	}

	public static InputStream getStreamFromURL(String imageURL) {
		InputStream in = null;
		try {
			URL url = new URL(imageURL);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			in = connection.getInputStream();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return in;

	}

	public static String getTimes(String time) {
		String r_time = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		Date d;
		try {
			d = sdf.parse(time);
			long l = d.getTime();
			String str = String.valueOf(l);
			r_time = str.substring(0, 10);
		} catch (ParseException e) {

		}
		return r_time;
	}

	public static String htmlRemoveTag(String inputString) {
		if (inputString == null)
			return null;
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		Pattern p_script;
		Matcher m_script;
		Pattern p_style;
		Matcher m_style;
		Pattern p;
		Matcher m_p;
		Pattern ps;
		Matcher m_ps;
		Pattern ds;
		Matcher d_ps;
		Pattern d;
		Matcher d_s;
		try {
			// 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
			// 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
			String regEx_p = "<p[^>]*?>"; // 定义p标签的正则表达式
			String regEx_ps = "<\\/p>";
			String regEx_d = "<div[^>]*?>"; // 定义p标签的正则表达式
			String regEx_ds = "<\\/div>";
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签
			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签
			p = Pattern.compile(regEx_p, Pattern.CASE_INSENSITIVE);
			m_p = p.matcher(htmlStr);
			htmlStr = m_p.replaceAll(""); // 过滤html标签
			ps = Pattern.compile(regEx_ps, Pattern.CASE_INSENSITIVE);
			m_ps = ps.matcher(htmlStr);
			htmlStr = m_ps.replaceAll("<br/>"); // 过滤html标签
			ds = Pattern.compile(regEx_ds, Pattern.CASE_INSENSITIVE);
			d_ps = ds.matcher(htmlStr);
			htmlStr = d_ps.replaceAll("");
			d = Pattern.compile(regEx_d, Pattern.CASE_INSENSITIVE);
			d_s = d.matcher(htmlStr);
			htmlStr = d_s.replaceAll("");
			textStr = htmlStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return textStr;// 返回文本字符串
	}

	public static String htmlRemoveTags(String inputString) {
		if (inputString == null)
			return null;
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		Pattern p_script;
		Matcher m_script;
		Pattern p_style;
		Matcher m_style;
		Pattern p;
		Matcher m_p;
		Pattern ps;
		Matcher m_ps;
		Pattern ds;
		Matcher d_ps;
		Pattern d;
		Matcher d_s;
		Pattern s;
		Matcher s_p;
		Pattern sp;
		Matcher sp_p;
		try {
			// 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
			// 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
			String regEx_p = "<p[^>]*?>"; // 定义p标签的正则表达式
			String regEx_ps = "<\\/p>";
			String regEx_d = "<div[^>]*?>"; // 定义p标签的正则表达式
			String regEx_ds = "<\\/div>";
			String regEx_sp = "<span[^>]*?>"; // 定义p标签的正则表达式
			String regEx_span = "<\\/span>";
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签
			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签
			p = Pattern.compile(regEx_p, Pattern.CASE_INSENSITIVE);
			m_p = p.matcher(htmlStr);
			htmlStr = m_p.replaceAll(""); // 过滤html标签
			ps = Pattern.compile(regEx_ps, Pattern.CASE_INSENSITIVE);
			m_ps = ps.matcher(htmlStr);
			htmlStr = m_ps.replaceAll(""); // 过滤html标签
			ds = Pattern.compile(regEx_ds, Pattern.CASE_INSENSITIVE);
			d_ps = ds.matcher(htmlStr);
			htmlStr = d_ps.replaceAll("");
			d = Pattern.compile(regEx_d, Pattern.CASE_INSENSITIVE);
			d_s = d.matcher(htmlStr);
			htmlStr = d_s.replaceAll("");
			sp = Pattern.compile(regEx_sp, Pattern.CASE_INSENSITIVE);
			sp_p = sp.matcher(htmlStr);
			htmlStr = sp_p.replaceAll("");
			s = Pattern.compile(regEx_span, Pattern.CASE_INSENSITIVE);
			s_p = s.matcher(htmlStr);
			htmlStr = s_p.replaceAll(" ");
			textStr = htmlStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return textStr;// 返回文本字符串
	}

	public static String stripHtml(String content) {

		// <p>段落替换为换行

		content = content.replaceAll("<p .*?>", "rn");

		// <br><br/>替换为换行

		content = content.replaceAll("<brs*/?>", "rn");

		// 去掉其它的<>之间的东西

		content = content.replaceAll("<.*?>", "");

		// 还原HTML

		// content = HTMLDecoder.decode(content);

		return content;

	}

	public static int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信息
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * 将图片按照某个角度进行旋转
	 * 
	 * @param bm
	 *            需要旋转的图片
	 * @param degree
	 *            旋转角度
	 * @return 旋转后的图片
	 */
	public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图片
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
					bm.getHeight(), matrix, true);
		} catch (OutOfMemoryError e) {
		}
		if (returnBm == null) {
			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;
	}

	public static String ToDbc(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	public static String ToSBC(String input) {
		char c[] = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == ' ') {
				c[i] = '\u3000';
			} else if (c[i] < '\177') {
				c[i] = (char) (c[i] + 65248);
			}
		}
		return new String(c);
	}

	public static String stringFilter(String str) {
		str = str.replaceAll("【", "[").replaceAll("】", "]")
				.replaceAll("！", "!").replaceAll("：", ":");// 替换中文标号
		String regEx = "[『』]"; // 清除掉特殊字符
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	public static int register(String path, Map<String, String> map) {
		int isRegSuccess = 0;
		Socket socket = new Socket();
		try {
			URL url = new URL(path);
			String host = url.getHost();
			int port = url.getDefaultPort();
			SocketAddress dest = new InetSocketAddress(host, port);
			socket.connect(dest);
		} catch (Exception e) {
			e.getMessage();
		}
		while (true) {
			try {
				// 创建一个流套接字并将其连接到指定主机上的指定端口号

				System.out.println("连接已经建立");
				// 将json转化为String类型
				JSONObject json = new JSONObject(map);
				String jsonString = "";
				jsonString = json.toString();
				// 将String转化为byte[]
				// byte[] jsonByte = new byte[jsonString.length()+1];
				byte[] jsonByte = jsonString.getBytes();
				DataOutputStream outputStream = null;
				outputStream = new DataOutputStream(socket.getOutputStream());
				System.out.println("发的数据长度为:" + jsonByte.length);
				outputStream.write(jsonByte);
				outputStream.flush();
				System.out.println("传输数据完毕");
				socket.shutdownOutput();

				// 读取服务器端数据
				DataInputStream inputStream = null;
				String strInputstream = "";
				inputStream = new DataInputStream(new BufferedInputStream(
						socket.getInputStream()));
				strInputstream = inputStream.readUTF();
				System.out.println("输入信息为：" + strInputstream);
				JSONObject js = new JSONObject(strInputstream);
				System.out.println(js.get("error"));
				isRegSuccess = Integer.parseInt((String) js.get("error"));
				// 如接收到 "OK" 则断开连接
				if (js != null) {
					System.out.println("客户端将关闭连接");
					Thread.sleep(500);
					break;
				}

			} catch (Exception e) {
				System.out.println("客户端异常:" + e.getMessage());
				break;
			} finally {
				if (socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						socket = null;
						System.out.println("客户端 finally 异常:" + e.getMessage());
					}
				}
			}
		}
		return isRegSuccess;
	}

	
	
	public static Bitmap ratio(String imgPath, int w, int h) {
		Bitmap bit = null;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		bit = BitmapFactory.decodeFile(imgPath, opts);
		int imageHeight = opts.outHeight;
		int imageWidth = opts.outWidth;
		int heightRatio = Math.round((float) imageHeight / (float) h);
		int widthRatio = Math.round((float) imageWidth / ((float) w));
		// opts.inSampleSize = heightRatio < widthRatio ? widthRatio :
		// heightRatio;
		// opts.inSampleSize = 2;
		opts.inJustDecodeBounds = false;
		try {
			bit = BitmapFactory.decodeFile(imgPath, opts);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		return bit;
	}

	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	public static int calculateInSampleSizes(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}
	public static boolean isWifiAvailable(Context ctx) {
		ConnectivityManager manager = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		return manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.isConnected();
	}
	public static Bitmap zoomBitmap(Bitmap bitmap) {
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		Matrix matrix = new Matrix();
		// float scaleWidth = ((float) width / w);
		// float scaleHeight = ((float) height / h);
		matrix.postScale(1.0f, 1.0f);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
		return newbmp;
	}

	public static Drawable zoomDrawables(Drawable drawable, int w, int h) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Bitmap oldbmp = drawableToBitmap(drawable);
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
				matrix, true);
		return new BitmapDrawable(null, newbmp);
	}

	private static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
				: Config.RGB_565;
		Bitmap bitmap = Bitmap.createBitmap(width, height, config);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);
		return bitmap;
	}

	public static Bitmap resize(Bitmap bitmap, int S) {
		int imgWidth = bitmap.getWidth();
		int imgHeight = bitmap.getHeight();
		double partion = imgWidth * 1.0 / imgHeight;
		double sqrtLength = Math.sqrt(partion * partion + 1); // 新的缩略图大小
		double newImgW = S * (partion / sqrtLength);
		double newImgH = S * (1 / sqrtLength);
		float scaleW = (float) (newImgW / imgWidth);
		float scaleH = (float) (newImgH / imgHeight);
		Matrix mx = new Matrix(); // 对原图片进行缩放
		mx.postScale(scaleW, scaleH);
		bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx,
				true);
		return bitmap;
	}

	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 30, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
		bitmapOptions.inSampleSize = 4;
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, bitmapOptions);// 把ByteArrayInputStream数据生成图片
		if (image != null && image.isRecycled()) {
			image.recycle();

		}
		return bitmap;
	}

	public static Drawable getDrawble(Context context, int resId) {
		Bitmap bitmap = null;
		BitmapFactory.Options opt = new BitmapFactory.Options();

		opt.inPreferredConfig = Config.RGB_565;

		opt.inPurgeable = true;

		opt.inInputShareable = true;

		// 获取资源图片
		try {
			InputStream is = context.getResources().openRawResource(resId);

			bitmap = BitmapFactory.decodeStream(is, null, opt);

			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return new BitmapDrawable(context.getResources(), bitmap);
	}
	/**
	 * 银行卡替换，保留后四位
	 *
	 * 如果银行卡号为空 或者 null ,返回null ；否则，返回替换后的字符串；
	 *
	 * @param bankCard 银行卡号
	 * @return
	 */
	public static String bankCardReplaceWithStar(String bankCard) {

		if (bankCard.isEmpty() || bankCard == null) {
			return null;
		} else {
			return replaceAction(bankCard, "(?<=\\d{0})\\d(?=\\d{4})");
		}
	}
	private static String replaceAction(String username, String regular) {
		return username.replaceAll(regular, "*");
	}

	public static Bitmap getImageFromData(byte[] data, int mMaxWidth,
			int mMaxHeight) {
		BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
		Bitmap bitmap = null;
		if (mMaxWidth == 0 && mMaxHeight == 0) {
			decodeOptions.inPreferredConfig = Config.RGB_565;
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
					decodeOptions);
		} else {
			// If we have to resize this image, first get the natural bounds.
			decodeOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
			int actualWidth = decodeOptions.outWidth;
			int actualHeight = decodeOptions.outHeight;

			// Then compute the dimensions we would ideally like to decode to.
			int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
					actualWidth, actualHeight);
			int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
					actualHeight, actualWidth);

			// Decode to the nearest power of two scaling factor.
			decodeOptions.inJustDecodeBounds = false;
			// TODO(ficus): Do we need this or is it okay since API 8 doesn‘t
			// support it?
			// decodeOptions.inPreferQualityOverSpeed =
			// PREFER_QUALITY_OVER_SPEED;
			decodeOptions.inSampleSize = findBestSampleSize(actualWidth,
					actualHeight, desiredWidth, desiredHeight);
			Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0,
					data.length, decodeOptions);

			// If necessary, scale down to the maximal acceptable size.
			if (tempBitmap != null
					&& (tempBitmap.getWidth() > desiredWidth || tempBitmap
							.getHeight() > desiredHeight)) {
				bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth,
						desiredHeight, true);
				tempBitmap.recycle();
			} else {
				bitmap = tempBitmap;
			}
		}
		return bitmap;
	}

	private static int findBestSampleSize(int actualWidth, int actualHeight,
			int desiredWidth, int desiredHeight) {
		double wr = (double) actualWidth / desiredWidth;
		double hr = (double) actualHeight / desiredHeight;
		double ratio = Math.min(wr, hr);
		float n = 1.0f;
		while ((n * 2) <= ratio) {
			n *= 2;
		}

		return (int) n;
	}

	private static int getResizedDimension(int maxPrimary, int maxSecondary,
			int actualPrimary, int actualSecondary) {
		// If no dominant value at all, just return the actual.
		if (maxPrimary == 0 && maxSecondary == 0) {
			return actualPrimary;
		}

		// If primary is unspecified, scale primary to match secondary‘s scaling
		// ratio.
		if (maxPrimary == 0) {
			double ratio = (double) maxSecondary / (double) actualSecondary;
			return (int) (actualPrimary * ratio);
		}

		if (maxSecondary == 0) {
			return maxPrimary;
		}

		double ratio = (double) actualSecondary / (double) actualPrimary;
		int resized = maxPrimary;
		if (resized * ratio > maxSecondary) {
			resized = (int) (maxSecondary / ratio);
		}
		return resized;
	}

	
	/*
     * This method was copied from http://stackoverflow.com/a/10028267/694378.
     * The only modifications I've made are to remove a couple of Log
     * statements which could slow things down slightly.
     */
    public static Bitmap fastblur(Bitmap sentBitmap, int radius) {

        // Stack Blur v1.0 from
        // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
        //
        // Java Author: Mario Klingemann <mario at quasimondo.com>
        // http://incubator.quasimondo.com
        // created Feburary 29, 2004
        // Android port : Yahel Bouaziz <yahel at kayenko.com>
        // http://www.kayenko.com
        // ported april 5th, 2012

        // This is a compromise between Gaussian Blur and Box blur
        // It creates much better looking blurs than Box Blur, but is
        // 7x faster than my Gaussian Blur implementation.
        //
        // I called it Stack Blur because this describes best how this
        // filter works internally: it creates a kind of moving stack
        // of colors whilst scanning through the image. Thereby it
        // just has to add one new block of color to the right side
        // of the stack and remove the leftmost color. The remaining
        // colors on the topmost layer of the stack are either added on
        // or reduced by one, depending on if they are on the right or
        // on the left side of the stack.
        //
        // If you are using this algorithm in your code please add
        // the following line:
        //
        // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = ( 0xff000000 & pix[yi] ) | ( dv[rsum] << 16 ) | ( dv[gsum] << 8 ) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
    }
   
	/**
	 * 根据路径删除图片
	 * 
	 * @param path
	 */
	public static void deleteTempFile(String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}
	/**
	 * 判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean isNullOrEmpty(Object obj) {
		
		
		if (obj != null){
			
		}else{
			return true;
		}
		
		if (obj.toString() != null){//判断对象（不知道对不对）
			
		}else{
			return true;
		}
		
		/*if (!isNullOrEmpty(obj.toString())){//判断对象（不知道对不对）0904|好像有错，以后在好好看一下
			Log.d("isNullOrEmpty", "=》》》》》》not null");
		}else{
			return true;
		}*/
		
		
		if (obj instanceof CharSequence){
			
			return ((CharSequence) obj).length() == 0;
		}
		if (obj instanceof Collection){
			
			return ((Collection) obj).isEmpty();
		}
			 
		if (obj instanceof Map){
			
			return ((Map) obj).isEmpty(); 
		}

		if (obj instanceof Object[]) {
			
			Object[] object = (Object[]) obj;
			if (object.length == 0) {
				return true;
			}
			boolean empty = true;
			for (int i = 0; i < object.length; i++) {
				if (!isNullOrEmpty(object[i])) {
					empty = false;
					break;
				}
			}
			return empty;
		}
		
		if (obj instanceof JSONArray) {
			if (((JSONArray)obj).length() == 0) {
				return true;
			}
		}
		
		if (obj instanceof JSONObject) {
			if (((JSONObject)obj).length() == 0) {
				return true;
			}
		}
		
		return false;
	}
	public static boolean isNumeric(String str){ 
	    Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
	//验证邮箱是否正确
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

	/**
	 * 读取路径中的图片，然后将其转化为缩放后的bitmap
	 * @param path
	 */
	public static String saveBefore(String path) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回bm为空
		options.inJustDecodeBounds = false;
		// 计算缩放比
		int be = (int) (options.outHeight / (float) 200);
		if (be <= 0)
			be = 1;
		options.inSampleSize = 4; // 图片长宽各缩小至四分之一
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
		bitmap = BitmapFactory.decodeFile(path, options);
		// savePNG_After(bitmap,path);
		return saveJPGE_After(bitmap, path);
	}
	/**
	 * 保存图片为JPEG
	 * @param bitmap
	 * @param path
	 */
	public static String saveJPGE_After(Bitmap bitmap, String path) {
		File file = new File(path);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return path;
	}

	public static String getStrTime(String  millis) {
		String re_StrTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		long lcc_time = Long.valueOf(millis);
		re_StrTime = sdf.format(new Date(lcc_time));
		return re_StrTime;
	}
	public static String getStrTimes(String  millis) {
		String re_StrTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		long lcc_time = Long.valueOf(millis);
		re_StrTime = sdf.format(new Date(lcc_time));
		return re_StrTime;
	}
	public static String secondToTime(long second){
		long days = second / 86400;            //转换天数
		second = second % 86400;            //剩余秒数
		long hours = second / 3600;            //转换小时
		second = second % 3600;                //剩余秒数
		long minutes = second /60;            //转换分钟
		second = second % 60;                //剩余秒数
		if(days>0){
			return days + "天" + hours + "小时" + minutes + "分" + second + "秒";
		}else{
			return hours + "小时" + minutes + "分" + second + "秒";
		}
	}
} 
